package com.ali.sso.common.shiro.filter;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.web.servlet.AdviceFilter;
import org.apache.shiro.web.util.WebUtils;

/**
 * Sid同步过滤器，用于跨域场景客户端应用从服务端同步sessionId
 * @author cwang
 */
public class SidSyncAdviceFilter extends AdviceFilter {
	static Log logger = LogFactory.getLog(SidSyncAdviceFilter.class);
	
	@Override
	protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		
		String service = WebUtils.getCleanParam(request, "service");
		String rememberMe = "false";
		Cookie[] cookies = httpRequest.getCookies();
		if(cookies != null){
			for (Cookie cookie : cookies) {
				if("rememberMe".equals(cookie.getName())){
					rememberMe = cookie.getValue();
					continue;
				}
			}
		}
		
		Session session = SecurityUtils.getSubject().getSession();
		//将hasSyn为true设置到session中，CasFilter会从Session中取该值
		session.setAttribute("hasSyn", true);
		String url = service + "?jsid=" + session.getId() + "&rememberMe=" + rememberMe;
		try {
			WebUtils.issueRedirect(request, response, url);
		} catch (IOException e) {
			logger.error(e);
		}
		
		//返回false，该次请求处理结束
		return false;
	}
	
}
